<script lang="ts" setup>
import { type Account, type AccountParam, updateAccount } from '@/api/UserAccountApi.ts'
import UploadImage from '@/component/Upload/UploadImage.vue'
import { useAccountStore } from '@/config/store/UseAccountStore.ts'
import { type ArcoForm, type ArcoFormRules, ArcoFormTool } from '@/tool/ArcoFormTool.ts'
import { Message } from '@arco-design/web-vue'
import { ObjectTool } from '@es-tool/core'
import { ref, toRaw } from 'vue'

const accountStore = useAccountStore()

const isLoading = ref(false)
const formRef = ref<ArcoForm | null>(null)

const formData = ref<AccountParam>(ObjectTool.copy(accountStore.account))
const formRule: ArcoFormRules<AccountParam> = {
    nickname: [ { required: true, message: '请输入昵称' } ],
    avatar: [ { required: true, message: '请上传头像' } ],
    email: [ { required: false, message: '请输入邮箱' } ],
    mobile: [ { required: false, message: '请输入手机号' } ],
}

function onFormSubmit(option: { errors: any, values: Account }, submitEvent: SubmitEvent) {
    console.debug('表单提交', {
        errors: toRaw(option.errors),
        data: toRaw(option.values),
        submitEvent,
    })

    isLoading.value = true
    ArcoFormTool.validate(formRef)
            .then(() => updateAccount(formData.value))
            .then(account => {
                accountStore.updateAccountInfo(account)
                formData.value = account
                Message.success('更新成功')
            })
            .finally(() => isLoading.value = false)
}

</script>

<template>
<div class="page-container">
    <a-spin :loading="isLoading" :size="32">
        <a-form
                ref="formRef"
                :model="formData"
                :rules="formRule"
                auto-label-width
                class="account-info-form"
                scroll-to-first-error
                @submit="onFormSubmit"
        >
            <a-form-item field="nickname" label="昵称">
                <a-input v-model="formData.nickname" placeholder="昵称" />
            </a-form-item>

            <a-form-item field="avatar" label="头像">
                <UploadImage v-model:uri="formData.avatar" />
            </a-form-item>

            <a-form-item field="email" label="邮箱">
                <a-input v-model="formData.email" placeholder="邮箱" />
            </a-form-item>

            <a-form-item field="mobile" label="手机号">
                <a-input v-model="formData.mobile" placeholder="手机号" />
            </a-form-item>

            <a-form-item>
                <a-button :loading="isLoading" html-type="submit">
                    提 交
                </a-button>
            </a-form-item>
        </a-form>
    </a-spin>
</div>
</template>

<style lang="scss" scoped>
.account-info-form {
    max-width: 800px;
}

:deep(.arco-spin) {
    display: block;
}
</style>
